package com.isoft.uaaservice.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import com.isoft.uaaservice.bean.LoginSysUserDetails;
import com.isoft.uaaservice.bean.SysPermission;
import com.isoft.uaaservice.bean.SysUser;
import com.isoft.uaaservice.dao.SysPermissionDao;
import com.isoft.uaaservice.dao.SysUserDao;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 *该类是UserDetailService的返回类型
 *封装登录用户的信息:添加登录用户对象成员
 *从UserDetails继承的get方法不能被序列化！！！
 *如果将当前类对象进行redis序列化存储，则要注意以上问题——从UserDetails继承
 的get方法序列化时忽略
 *【否则，发序列化时发生异常】
 **/
@Slf4j
@Service
@Transactional
public class SysUserDetailService implements UserDetailsService {
    @Autowired
    SysUserDao sysUserDao;
    @Autowired
    SysPermissionDao sysPermissionDao;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 根据用户名去查询数据库对应数据
        QueryWrapper<SysUser> wrapper = new QueryWrapper<>();
        wrapper.eq("username", username);
        SysUser sysUser = sysUserDao.selectOne(wrapper);
        if (null == sysUser || sysUser.getIslock() == 1){
            log.error("所查找的用户名不存在！");
            throw new RuntimeException("用户 '" + username + "' 不存在");
        }


        //TODD :
        // 从数据库中读取用户的权限列表
        System.out.println("-----------------------------------SysUserDetailService-1");
        List<SysPermission> permissionList = sysPermissionDao.topPermissionByUserid(sysUser.getId());
        System.out.println("-----------------------------------SysUserDetailService-2");

        //for循环遍历方法 : 遍历权限列表，将权限字符串添加到 allowList 中
        List<String> allowList = new ArrayList<>() ;
        for (SysPermission permission : permissionList){
            allowList.add(permission.getUrl());
        }
        System.out.println("用户id为"+sysUser.getId()+"的权限列表" + allowList);
        System.out.println("-----------------------------------SysUserDetailService-3");
        return new LoginSysUserDetails(sysUser ,allowList);
    }
}
